package com.ruoyi.system.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.constant.ActivityConstant;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.group.AddGroup;
import com.ruoyi.common.group.UpdateGroup;

import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.VerificationCode;
import com.ruoyi.system.api.RemoteSearchService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SchoolRole;

import com.ruoyi.system.domain.Tribe;
import com.ruoyi.system.domain.UserDetail;
import com.ruoyi.system.service.*;

import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.system.domain.Activity;


/**
 * 活动信息管理表Controller
 * 
 * @author hyb
 * @date 2023-01-20
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/activity/activity")
public class ActivityController extends BaseController
{
    @Autowired
    private IActivityService activityService;

    @Autowired
    private ITribeService tribeService;

    @Autowired
    private ISchoolRoleService schoolRoleService;


    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    ISysUserService userService;

    @Autowired
    ISysConfigService configService;


    @Autowired
    RemoteSearchService remoteSearchService;

    @Autowired
    IUserDetailService userDetailService;

    /*
    * 查询热度高的几个活动
    * */
    @InnerAuth
    @GetMapping("/indexHotCount")
    public AjaxResult indexHotCount(){
        String s = configService.selectConfigByKey("sys.indexActivity.number");
        List<Activity> list=activityService.selectActivityByMaxHotCountAsc(Long.parseLong(s));
        return AjaxResult.success().put("list",list);
    }

    /*
    * 计算全校活动数量
    * */
    @RequiresPermissions("activity:activity:count")
    @GetMapping("/count")
    public AjaxResult count(){
        int count=activityService.countActivity(new Activity());
        return AjaxResult.success().put("count",count);
    }

    /*
    * 计算正在审核通过的
    * */

    @RequiresPermissions("activity:activity:countChecked")
    @GetMapping("/countChecked")
    public AjaxResult countChecked(){
        Activity activity = new Activity();
        activity.setStatus(ActivityConstant.APPROVE_FINAL);
        int count=activityService.countApproveLog(activity);
        return AjaxResult.success().put("count",count);
    }

    /*
    * 计算正在开始的
    * */
    @RequiresPermissions("activity:activity:countStarting")
    @GetMapping("/countStarting")
    public AjaxResult countStarting(){
        Activity activity = new Activity();
        activity.setStatus(ActivityConstant.STARTING_STATUS);
        int count=activityService.countActivity(activity);
        return AjaxResult.success().put("count",count);
    }




    /**
     * 查询活动信息管理表列表
     */

    @RequiresPermissions("activity:activity:list")
    @GetMapping("/list")
    public TableDataInfo list(Activity activity)
    {
//        activity.setUserId(SecurityUtils.getUserId());
        startPage();
        List<Activity> list = activityService.selectActivityList(activity);
        return getDataTable(list);
    }

    /**
     * 导出活动信息管理表列表
     */
    @RequiresPermissions("activity:activity:export")
    @Log(title = "活动信息管理表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Activity activity)
    {
        List<Activity> list = activityService.selectActivityList(activity);
        ExcelUtil<Activity> util = new ExcelUtil<Activity>(Activity.class);
        util.exportExcel(response, list, "活动信息管理表数据");
    }

    /**
     * 获取活动信息管理表详细信息
     */
    @RequiresPermissions("activity:activity:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(activityService.selectActivityById(id));
    }

    @InnerAuth
    @GetMapping(value = "/inner")
    public AjaxResult getInfoByInnerAuth(@RequestParam("id") Long id)
    {
        Activity activity = activityService.selectActivityById(id);
        return AjaxResult.success().put("activity",activity);
    }


    /*
    * 判断是否存在该活动
    * */
    @InnerAuth
    @GetMapping("/check")
    public AjaxResult checkInfo(@RequestParam("id") Long id){
        Activity activity = activityService.selectActivityById(id);
        return activity==null?AjaxResult.error("活动不存在"):AjaxResult.success().put(ActivityConstant.NAME,activity);
    }

    /**
     * 新增活动信息管理表
     */
    @RequiresPermissions("activity:activity:add")
    @Log(title = "活动信息管理表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated(AddGroup.class)@RequestBody Activity activity, @RequestParam(value = "isTribe",defaultValue = "false")boolean isTribe)
    {
        if(!isTribe) activity.setTribeId(ActivityConstant.NOT_TRIBE_ID);
        else{
            //如果是部落活动
            //看看验证码是否正确
            String key="tribe::"+activity.getTribeId();
            String s = redisTemplate.boundValueOps(key).get();
            if(StringUtils.isEmpty(s)){
                return AjaxResult.error("验证码不正确!");
            }
        }
        //主办方ID,也就是部落是否存在,指导老师是否存在,
        List<Tribe> tribes = tribeService.selectTribeByNumber(activity.getPrepareField4());
        if(tribes.size()==0){
            return AjaxResult.error("主办方ID不存在!");
        }
        SchoolRole s = new SchoolRole();
        s.setDeptId(activity.getId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(s);
        if(schoolRoles.size()==0){
            return AjaxResult.error("指导老师不存在!");
        }
        s=schoolRoles.get(0);
        activity.setNumber(VerificationCode.getNumberString(9));
        //设置负责人
        activity.setUserId(SecurityUtils.getUserId());
        activity.setPrepareField2(s.getName());

        //检查时间是否合理
        Date lastTime = activity.getLastTime();
        Date startTime = activity.getStartTime();
        Date signupTime = activity.getSignupTime();
        if(DateUtils.compareDate(lastTime,startTime)==-1){
            return AjaxResult.error("结束时间不能早于开始时间!");
        }
        if(DateUtils.compareDate(startTime,signupTime)==-1){
            return AjaxResult.error("报名时间不能晚于开始时间!");
        }


        int i = activityService.insertActivity(activity);

        redisTemplate.opsForValue().set(ActivityConstant.ACTIVITY_INTRODUCE_KEY+activity.getId(),activity.getIntroduce());


        //远程调用插入到elasticSearch里
        com.ruoyi.system.api.domain.Activity ap = new com.ruoyi.system.api.domain.Activity();
        BeanUtils.copyProperties(activity,ap);
        remoteSearchService.insert(ap, SecurityConstants.INNER);

        return toAjax(i);
    }

    /**
     * 修改活动信息管理表
     */
    @RequiresPermissions("activity:activity:edit")
    @Log(title = "活动信息管理表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated(UpdateGroup.class) @RequestBody Activity activity, @RequestParam(value = "isTribe",defaultValue = "false")boolean isTribe)
    {
        if(!isTribe) activity.setTribeId(ActivityConstant.NOT_TRIBE_ID);
        else{
            //如果是部落活动
            //看看验证码是否正确
            String key="tribe::"+activity.getTribeId();
            String s = redisTemplate.boundValueOps(key).get();
            if(StringUtils.isEmpty(s)){
                return AjaxResult.error("验证码不正确!");
            }
        }

        Activity at = activityService.selectActivityById(activity.getId());
        if (!at.getStatus().equals(ActivityConstant.CREATE_STATUS) && !at.getStatus().equals(ActivityConstant.APPROVE_REJECT)){
            return AjaxResult.error("只有刚创建活被驳回的活动才能修改!");
        }

        Long userId = at.getUserId();
        Long id = SecurityUtils.getUserId();
        if (!Objects.equals(userId, id)){
            return AjaxResult.error("只有创建人才可以修改该活动!");
        }


        //主办方ID,也就是部落是否存在,指导老师是否存在,
        List<Tribe> tribes = tribeService.selectTribeByNumber(activity.getPrepareField4());
        if(tribes.size()==0){
            return AjaxResult.error("主办方ID不存在!");
        }
        SchoolRole s = new SchoolRole();
        SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
        s.setDeptId(sysUser.getDeptId());
        List<SchoolRole> schoolRoles = schoolRoleService.selectSchoolRoleList(s);
        if(schoolRoles.size()==0){
            return AjaxResult.error("指导老师不存在!");
        }


        //规定不能修改的字段
        activity.setRemoveTime(null);
        activity.setThumbCount(null);
        activity.setHotCount(null);
        activity.setStatus(null);
        activity.setLastIntegral(null);
        activity.setNumber(null);
        activity.setUserId(null);
        activity.setLastPersonCount(null);
        activity.setSignupCount(null);
        activity.setPublishTime(null);

        //检查时间是否合理
        Date lastTime = activity.getLastTime();
        Date startTime = activity.getStartTime();
        Date signupTime = activity.getSignupTime();
        if(DateUtils.compareDate(lastTime,startTime)==-1){
            return AjaxResult.error("结束时间不能早于开始时间!");
        }
        if(DateUtils.compareDate(startTime,signupTime)==-1){
            return AjaxResult.error("报名时间不能晚于开始时间!");
        }

        int i = activityService.updateActivity(activity);
        //更新es索引数据

        redisTemplate.opsForValue().set(ActivityConstant.ACTIVITY_INTRODUCE_KEY+activity.getId(),activity.getIntroduce());

        com.ruoyi.system.api.domain.Activity ap = new com.ruoyi.system.api.domain.Activity();
        BeanUtils.copyProperties(activity,ap);
        remoteSearchService.update(ap,SecurityConstants.INNER);

        return toAjax(i);
    }


    /**
     * 删除活动信息管理表
     */
    @RequiresPermissions("activity:activity:remove")
    @Log(title = "活动信息管理表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        //只有创建人才能删除
        return toAjax(activityService.deleteActivityByIds(ids));
    }



}
